package com.test4;

import cn.hutool.core.codec.Base64;
import org.apache.commons.codec.binary.Hex;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.MessageDigest;

public class Md5CaculateUtil {


    /**
     * 获取网络图片 md5
     * @param URLName 网络图片地址
     * */
    public static String getMD5ByUrl(String URLName) {

        try {

            URL url = new URL(URLName);
            InputStream inputStream = new BufferedInputStream(url.openStream());
            return getMD5(inputStream);

        } catch (Exception e) {

            throw new RuntimeException(e.getLocalizedMessage());

        }

    }

    /**
     * 获取一个文件的md5值(可处理大文件)
     * @return md5 value
     */
    public static String getMD5(InputStream inputStream) {
        try {
            MessageDigest MD5 = MessageDigest.getInstance("MD5");
            byte[] buffer = new byte[8192];
            int length;
            while ((length = inputStream.read(buffer)) != -1) {
                MD5.update(buffer, 0, length);
            }
            return new String(Hex.encodeHex(MD5.digest()));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }


    public static InputStream getInputStream(String uri){
        try {

            URL url = new URL(uri);
            InputStream inputStream = new BufferedInputStream(url.openStream());
            return inputStream;
        } catch (Exception e) {
            throw new RuntimeException(e.getLocalizedMessage());
        }
    }

    /**

     * 将图片转换成Base64编码

     * @return

     */

    public static String getImgStr(InputStream in){
        return Base64.encode(in);
    }

    public static String getImgStr(String uri){
        return getImgStr(getInputStream(uri));
    }


}
